<?php
/**
 * Created by PhpStorm.
 * User: fengbob
 * Date: 2018/2/23
 * Time: 14:30
 */

namespace app\models;


use app\librarys\Tools;
use app\librarys\ZfbService;
use app\models\db\MiniPrograms;
use app\models\db\TUser;
use yii\db\Query;

class TUserExt extends TUser
{
    const USER_TOKEN_MINI_KEY='user_token_mini_key';
    const USER_TOKEN_KEY = 'user_token_ken';
    const USER_TOKEN_ESHOPExpiresIn = 60 * 60 * 24 * 7;  // user token 过期时间为7天

    const  ZFB_APP_ID_PRE_STR='zfb_app_id';
    const ZFB_LOGIN_STR = 'zfb_login_str';

    private static $user = null;

    /**
     * 客户端无缓存token情况下，调用此接口，此接口生成新token
     * @param $app_id
     */
    public static function touristLogin($app_id){
        $mini_program = self::getByAppId($app_id);
        $token = self::createTourist($mini_program);
        return $token;
    }

    /**
     * 创建游客
     * @param $mini_program_id
     */
    private static function createTourist($mini_program){
        $token = Tools::uuid();
//        $cache = \Yii::$app->cache;
//        $cache->set(self::USER_TOKEN_KEY.$token);
//        var_dump($mini_program['id']);
        $user = self::createTuserByZfbId('游客'.Tools::uuid(),$mini_program['id']);
        self::_setMiniProgramUserToken($token,$mini_program);
        self::_setUserToken($token,$user);
        return $token;
    }

    /**
     * 用户登录
     * @param $app_id
     * @param $auth_code
     */
    public static function login($app_id,$auth_code,$nickName,$avatar){


        // 獲取mini_programs
        $mini_program = self::getByAppId($app_id);
        //支付寶服務區登錄 並緩存
        $zfb_login_data = ZfbService::getAuthToken($auth_code,$mini_program);
        $tuser = TUser::findOne(['zfb_openid'=>$zfb_login_data['user_id'],'mini_programes'=>$mini_program['id']]);
        if(empty($tuser))
            self::createTuserByZfbId($zfb_login_data['user_id'],$mini_program['id']);
         $tuser->name = $nickName;
         $tuser->header_url = $avatar;

        self::_setMiniProgramUserToken($zfb_login_data['access_token'],$mini_program);
        self::_setUserToken($zfb_login_data['access_token'],$tuser);

        if(empty($zfb_login_data) || empty($zfb_login_data['access_token']))
            return '';
        return $zfb_login_data['access_token'];
    }


    public static function getByAppId($app_id)
    {

//        \Yii::$app->cache->flush();
        //读取缓存
        $cache = \Yii::$app->cache;
        $data = $cache->get(self::ZFB_APP_ID_PRE_STR.$app_id);

        if (empty($data) || $data == false) {
            //这里我们可以操作数据库获取数据，然后通过$cache->set方法进行缓存
//            $cacheData = ......
//            $data = (new Query())
//                ->select('*')
//                ->from('t_mini_programs')
//                ->where(['app_id'=>$app_id])
//                ->one();
            $data = MiniPrograms::find(['app_id'=>$app_id])
                ->one();
            //set方法的第一个参数是我们的数据对应的key值，方便我们获取到
            //第二个参数即是我们要缓存的数据
            //第三个参数是缓存时间，如果是0，意味着永久缓存。默认是0
            $cache->set(self::ZFB_APP_ID_PRE_STR.$app_id, $data, 0);
//            $data = $mini;

        }
        return $data;
    }

    public static function getZFBCurrentUser($access_token){
        $cache = \Yii::$app->cache;
        $user = $cache->get(self::USER_TOKEN_KEY.$access_token);
        //缓存没有，在数据库里面查询
        if(empty($user)){
            $user = TUser::findOne(['token'=>$access_token]);
            self::_setUserToken($access_token,$user);
        }
        self::$user = $user;
       return $user;
    }

    public static function getZFBCurrentMiniProgram($access_token){
        $cache = \Yii::$app->cache;
        $mini = $cache->get(self::USER_TOKEN_MINI_KEY.$access_token);
        if(empty($mini))
        {
           $user = self::getZFBCurrentUser($access_token);
//            $mini = self::$user->mini_programes();
            $mini = $user->miniProgrames;
            self::_setMiniProgramUserToken($access_token,$mini);
        }
        return $mini;
    }

    private static function _setMiniProgramUserToken($user_token,$mini_program){
        // 设置token之前,先将此userId用户以前所用的token清除,已保证每个用户同时只有一个token有效。
        $token_cache = \yii::$app->cache->get(self::USER_TOKEN_MINI_KEY.$user_token);
        if($token_cache != false){
            \yii::$app->cache->delete(self::USER_TOKEN_MINI_KEY.$user_token);
        }

        \yii::$app->cache->set(self::USER_TOKEN_MINI_KEY.$user_token,$mini_program,self::USER_TOKEN_ESHOPExpiresIn);
    }

    private static function _setUserToken($user_token,$user){
        // 设置token之前,先将此userId用户以前所用的token清除,已保证每个用户同时只有一个token有效。
        $token_cache = \yii::$app->cache->get(self::USER_TOKEN_KEY.$user_token);
        if($token_cache != false){
            \yii::$app->cache->delete(self::USER_TOKEN_KEY.$user_token);
        }

        \yii::$app->cache->set(self::USER_TOKEN_KEY.$user_token,$user,self::USER_TOKEN_ESHOPExpiresIn);
        $user->token = $user_token;
        $user->save();

    }

    public static function getTuserByZfbId($zfb_user_id,$mini_programs_id){
        return TUser::findOne(['zfb_openid'=>$zfb_user_id,'mini_']);
    }

    public static function createTuserByZfbId($zfb_user_id,$mini_programs_id){
        $tuser = new TUser();
        $tuser->id = Tools::uuid();
        $tuser->zfb_openid = $zfb_user_id;
        $tuser->mini_programes = $mini_programs_id;
        $tuser->is_enable = 1;

        $tuser->save();
        return $tuser;
    }

    /**
     * 列表
     * @param int $page
     * @param int $pageSize
     * @param string $name
     * @return mixed
     */
    public static function getTUserList($page = 0, $pageSize = 20, $name = '')
    {
        if ($page <= 0) $page = 0;
        $start = $page * $pageSize;

//        $query = (new Query())
//            ->select(['t1.*','t2.'])
//            ->from('t_order as t1')
//            ->leftJoin('t_goods as t2','t1.')


        $items = TUser::find()
            ->where(['is_enable'=>1])
            ->orFilterWhere(['like', 'name', $name])
            ->orFilterWhere(['like', 'phone', $name])
            ->orderBy('create_datetime desc')
            ->limit($pageSize)
            ->offset($start)
            ->all();
        return $items;
    }
    /**
     * 数量
     * @param string $name
     * @return int|string
     */
    public static function getTUserCount($name = '')
    {
        return db\TUser::find()
            ->where(['is_enable'=>1])
            ->orFilterWhere(['like', 'name', $name])
            ->orFilterWhere(['like', 'phone', $name])
            ->count();
    }

    /**
     *  根据id获取行
     * @param $id
     * @return array|null|\yii\db\ActiveRecord
     */
    public static function getTUserById($id)
    {
        $item = db\TUser::findOne($id);

        return $item;
    }


}